using Gtk;
using System;
using System.Data;

namespace Serpis
{


	/// <summary>
	/// Rellena el comboBox ejecutando el commandText sobre la dbConnection indicados en el constructor.
	/// El Id establece y devuelve la clave primaria activa en el combo.
	/// </summary>
	internal class ComboBoxHelper
	{
		private ComboBox comboBox;
		private IDbCommand dbCommand;
		private ListStore listStore;
		
		public ComboBoxHelper (ComboBox comboBox, IDbConnection dbConnection, string commandText)
		{
			this.comboBox = comboBox;
			dbCommand = dbConnection.CreateCommand();
			dbCommand.CommandText = commandText;
		}
		
		public string Id {
			get {
				if (listStore == null) 
					init("");
				TreeIter treeIter;
				comboBox.GetActiveIter(out treeIter);
				return (string)listStore.GetValue(treeIter, 0);
			}
			set {
				if (listStore == null) 
					init(value);
				else {
					TreeIter treeIter;
					if (!listStore.GetIterFirst(out treeIter))
						return;
					do {
						if (value == (string)listStore.GetValue(treeIter, 0)) {
							comboBox.SetActiveIter(treeIter);
							break;
						}
					} while (listStore.IterNext(ref treeIter));
				}
			}
		}
		
		private void init(string id)
		{
			CellRendererText cellRendererText = new CellRendererText();
			comboBox.PackStart(cellRendererText, false);
			comboBox.AddAttribute(cellRendererText, "text", 1);
			
			listStore = new ListStore(typeof(string), typeof(string));
			TreeIter treeIter = listStore.AppendValues("", "<vacio>");
			IDataReader dataReader = dbCommand.ExecuteReader();
			while (dataReader.Read()) {
				string currentId = dataReader[0].ToString();
				TreeIter currentTreeIter = listStore.AppendValues(currentId, dataReader[1].ToString());
				if (currentId == id)
					treeIter = currentTreeIter;
			}
			
			dataReader.Close();
			comboBox.Model = listStore;
			comboBox.SetActiveIter(treeIter);
			
			comboBox.Changed += delegate {
				raiseChanged();				
			};
		}
		
		private void raiseChanged()
		{
			if (Changed != null)
				Changed(this, EventArgs.Empty);
		}
		
		public event EventHandler Changed;
	}
}
